/*******************************************************************************
 * Copyright (c) 2011 Technische Universität Darmstadt
 * 					  Fachbereich Informatik
 * 					  Theoretische Informatik - Kryptographie und Computeralgebra
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 ******************************************************************************/

package de.tud.cdc;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openpgp.PGPEncryptedData;
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPLiteralData;
import org.bouncycastle.openpgp.PGPLiteralDataGenerator;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPPublicKeyRingCollection;
import org.bouncycastle.openpgp.PGPUtil;
import org.bouncycastle.util.encoders.Base64;

/**
 * Class handling the PGP subject encryption.
 * 
 * @author Franziskus Kiefer, Christian Kirschner
 * 
 */
public class SubjectEncryption {

	public String encryptSubject(String[] userIDs, String subject, String pubringPath, String pubringFile) {
		Security.addProvider(new BouncyCastleProvider());
		Collection<PGPPublicKey> keys = new ArrayList<PGPPublicKey>();
		String result = "";
		String address;

		for (int i = 0; i < userIDs.length; i++) {
			String[] split = userIDs[i].split("<");
			if (split.length < 2) {
				address = userIDs[i];
			} else {
				address = split[1];
			}
			PGPPublicKey key = getPublicKey(address, pubringPath, pubringFile);
			if (key != null)
				keys.add(key);
			else
				result += ", " + userIDs[i];
		}
		if (keys.size() < userIDs.length)
			return "--NO KEY--" + result.substring(2);
		return encryptSubject(subject, keys);
	}

	@SuppressWarnings("unchecked")
	public PGPPublicKey getPublicKey(String userID, String pubringPath, String pubringFile) {
		try {
			if (!pubringPath.endsWith(System.getProperty("file.separator"))) pubringPath+=System.getProperty("file.separator");
			FileInputStream keyInStream = new FileInputStream(pubringPath + pubringFile);
			PGPPublicKeyRingCollection keyRing = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(keyInStream));
			
			Iterator<PGPPublicKeyRing> it = keyRing.getKeyRings(userID, true, true);
			PGPPublicKey key = null;
			while (it.hasNext()) {
				Iterator<PGPPublicKey> keyIt = it.next().getPublicKeys();
				while(keyIt.hasNext()){
					keyIt.next(); //Subkey is used for encryption
					key = keyIt.next();
					if (key.isEncryptionKey())
						break;
				}
				boolean error = false;
				try {
					System.out.println("Encryption algorithm: " + key.getKey("BC").getAlgorithm());
				} catch (Exception e) {
					error = true;
					e.printStackTrace();
				}
				if (!error)
					return key;
			}
		} catch (PGPException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public String encryptSubject(String subject, Collection<PGPPublicKey> encKey) {
		try {
			boolean withIntegrityCheck = false;
			PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(PGPEncryptedData.CAST5, withIntegrityCheck, new SecureRandom(), "BC");
			for (PGPPublicKey key : encKey)
				encGen.addMethod(key);
			byte[] text = subject.getBytes("UTF-8");
			ByteArrayOutputStream bOut = new ByteArrayOutputStream();
			PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator();
			OutputStream lOut = lGen.open(bOut, PGPLiteralData.BINARY, PGPLiteralData.CONSOLE, text.length, new Date());
			lOut.write(text);
			lGen.close();
			byte[] bytes = bOut.toByteArray();

			ByteArrayOutputStream out = new ByteArrayOutputStream();
			OutputStream cOut = encGen.open(out, bytes.length);

			cOut.write(bytes);
			cOut.close();
			out.close();

			byte[] encryptedData = out.toByteArray();
			encryptedData = Base64.encode(encryptedData);
			return new String(encryptedData);
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
		} catch (PGPException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "--NO KEY--";
	}

}
